<template>
  <div>
    <!--    <h1>用户管理</h1>-->
    <div class="app-container">
      <n-card>
        <div>
          <n-button type="primary" @click="handleAddUser" v-auth="'system-user-add'">添加用户</n-button>
        </div>
        <n-data-table class="m-t-10" size="small" :columns="columns" :data="tableData"
                      :single-line="false"></n-data-table>
        <pagination :get-list="getList" :total="total" />
      </n-card>
    </div>
    <c-modal @register="modalRegister" @on-ok="handleSubmit" style="width: 600px"
             :title="`${ isCreate ? '添加' : '编辑' }系统用户`">
      <n-card>
        <n-form
            label-width="100"
            label-align="left"
            class="m-t-20"
            :model="form"
            :rules="formRules"
            ref="formRef"
            label-placement="left">
          <n-form-item label="用户名称:" path="userName">
            <n-input placeholder="请输入用户名称" v-model:value="form.userName"/>
          </n-form-item>
          <n-form-item label="登录账号:" path="account" >
            <n-input placeholder="请输入用户登录账号" :disabled="!isCreate" v-model:value="form.account"/>
          </n-form-item>
          <n-form-item label="登录密码:" path="password" v-if="isCreate">
            <n-input placeholder="请输入用户登录账号" v-model:value="form.password"/>
          </n-form-item>
          <n-form-item label="用户角色:">
            <n-select
                placeholder="请选择用户角色"
                v-model:value="form.roleIds"
                clearable
                multiple
                :options="allRole"
                :max-tag-count="3"
            />
          </n-form-item>
          <n-form-item label="用户状态:" path="status">
            <n-radio-group v-model:value="form.status">
              <n-space>
                <n-radio :value="1101">启用</n-radio>
                <n-radio :value="1102">禁用</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-form>
      </n-card>
    </c-modal>
  </div>
</template>

<script setup lang="ts">
import { tableColumns, formRules, FormType, baseForm } from './data/user'
import { CModal, useModal } from '../../components/Modal'
import { useConfirm } from "../../components/confirm";
import { Ref, ref } from "vue";
import { isEmpty } from '../../utils/is';
import { syncValidate } from "../../utils/common";
import { useMessage } from 'naive-ui'
const { confirmWarning } = useConfirm()
const message = useMessage();
import { apiRoleAll } from "../../api/system/role";
import { apiAdminRegister, apiAdminPage, apiUpdateAdminInfo,apiAdminDelete } from '../../api/user';
import { Pagination,usePagination } from "../../components/pagination";
import {PageType} from "../../types/global";

/** 初始化表格数据 */
const columns = tableColumns({
  // 更新
  updateFn: async (row: any) => {
    let roleIds = row.roles.map((item: FormType) =>  item.id)
    form.value = { ...row, roleIds }
    isCreate.value = false;
    openModal();
  },
  // 删除
  deleteFn: async (row: any) => {
    await confirmWarning();
    await apiAdminDelete([row.id]);
    message.success(`删除用户成功`);
    await getList()
  }
})

/** 获取用户列表 */
let tableData: Ref<Array<FormType>> = ref([])
let total:Ref<number> = ref(0)
const { initGetList } = usePagination()
let getList = initGetList(async (pageData) => {
  let { data } = await apiAdminPage(pageData as PageType);
  tableData.value = data.rows;
  total.value = data.count;

})
getList();

/** 获取所有角色 */
let allRole: Ref<any[]> = ref([])

async function getAllRole() {
  allRole.value = await apiRoleAll();
}

getAllRole();

/** 添加，编辑用户 */
const form: Ref<FormType> = ref(baseForm());
let formRef: any = ref()
let isCreate: Ref<boolean> = ref(false)

const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({});

function handleAddUser() {
  isCreate.value = true;
  form.value = baseForm();
  openModal();
}

/** 确认添加或者修改 */
async function handleSubmit(e: Event) {
  e.preventDefault()
  try {
    await syncValidate(formRef)
    if (isCreate.value) {
      await apiAdminRegister(form.value)
    } else {
      await apiUpdateAdminInfo(form.value)
    }
    message.success(`${ isCreate.value ? '添加' : '更新' }用户成功`);
    setSubLoading(false);
    closeModal();
    await getList()
  } catch (e) {
    message.warning('请正确填写信息');
    setSubLoading(false)
  }
}

</script>

<style scoped>

</style>
